package com.study.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Service
public class MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private TemplateEngine templateEngine;

    //发送简单邮件
    public void sendSimpleEmail(String to, String subject, String context) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("15673745355@163.com");
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(context);
        try {
            mailSender.send(simpleMailMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //发送带附件的邮件
    public void sendAttchEmail(String to, String subject, String context) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("15673745355@163.com");
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(context);
            //添加附件
            String filePath = "/home/x/test.txt";
            FileSystemResource resource = new FileSystemResource(filePath);
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, resource);

            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    //发送thymeleaf邮件
    public void sendTemlateEmail(String to, String subject, String context) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("15673745355@163.com");
            helper.setTo(to);
            helper.setSubject(subject);

            Context contextThymeLeaf = new Context();
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("id", "51");
            hashMap.put("code", "2222");
            contextThymeLeaf.setVariables(hashMap);
            String mailContext = templateEngine.process("email", contextThymeLeaf);
            helper.setText(mailContext, true);

            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
